package timer

import (
	"time"
)

const DateTimeLayout = "2006-01-02 15:04:05"
const TimeLayout = "15:04:05"
const DateLayout = "2006-01-02"
const DateLayout1 = "20060102"
const HourStatLayout = "2006010215"
const DayLayout1 = "20060102"
const FullLayout1 = "20060102150405"
const MinuteLayout1 = "200601021504"

const BeiJingZone = "Etc/GMT-8"

// 解析时间戳到不同时区的时间
// ttt, _ := timer.ParseTimestampWithLocation("Etc/GMT-8", 1579137428)
// 不同时区对同一时间戳 时间不同
// time 结构体是包含时区概念的, 默认是UTC
func ParseTimestampWithLocation(locationName string, timestamp int64) (time.Time, error) {
	str := time.Unix(timestamp, 0).Format(DateTimeLayout)
	loc, err := time.LoadLocation(locationName)
	if err != nil {
		return time.Time{}, err
	} else {
		lt, _ := time.ParseInLocation(DateTimeLayout, str, loc)
		return lt, nil
	}

}

func SetTimezonePRC() {
	timeLocal, _ := time.LoadLocation(BeiJingZone)
	time.Local = timeLocal
}

func GetPRCCurTimeStr() string {
	return time.Now().Format(DateTimeLayout)
}

// 使用UTC解析时间戳
func ParseTimestamp2Time(timestamp int64) *time.Time {
	t := time.Unix(int64(timestamp), 0).UTC()
	return &t
}

func ParseTimeStringWithLocation(locationName string, timeString string) (time.Time, error) {
	loc, err := time.LoadLocation(locationName)
	if err != nil {
		return time.Time{}, err
	} else {
		lt, _ := time.ParseInLocation(DateTimeLayout, timeString, loc)
		return lt, nil
	}

}

// 解析带有时区信息的时间字符串  如 "2017-03-14T16:09:54Z"
// ISO 8601
func ParseTimeStrRFC3339(timeStr string) int64 {
	if timeStr == "" {
		return 0
	}
	t, _ := time.Parse(time.RFC3339, timeStr)
	return t.Unix()
}

// 将时间戳转成ISO 8601格式的时间格式
func ParseTimestampRFC3339(timestamp int64) string {
	if timestamp == 0 {
		return ""
	}
	str := time.Unix(int64(timestamp), 0).UTC().Format(time.RFC3339)
	return str
}

func ParseTimeStrByLayout(timeStr string, layout string) int64 {
	if timeStr == "" {
		return 0
	}
	t, _ := time.Parse(layout, timeStr)
	return t.Unix()
}

// 将时间戳转成ISO 8601格式的时间格式
func ParseTimestampByLayout(timestamp int64, layout string) string {
	if timestamp == 0 {
		return ""
	}
	str := time.Unix(int64(timestamp), 0).UTC().Format(layout)
	return str
}

func Time2Unix(t *time.Time) int64 {
	if t == nil {
		return 0
	}
	return t.Unix()
}

func GetFloatCurTimestamp() float64 {
	now := time.Now().Unix()
	return float64(now)
}
